import { createApp } from 'vue'
import CustomModal from '@/components/CustomModal.vue'
import { toastService } from './toastService'

class ModalService {
  constructor() {
    this.modals = []
  }

  // Alert 弹窗
  alert(message, options = {}) {
    // 同时显示Toast提示
    toastService.show(message, {
      title: options.title || '提示',
      variant: options.variant || 'info',
      duration: options.duration || 4000
    })
    
    return new Promise((resolve) => {
      this.createModal({
        type: 'alert',
        message,
        title: options.title || '提示',
        variant: options.variant || 'info',
        confirmText: options.confirmText || '确定',
        onConfirm: resolve,
        onCancel: resolve
      })
    })
  }

  // Confirm 弹窗
  confirm(message, options = {}) {
    return new Promise((resolve) => {
      this.createModal({
        type: 'confirm',
        message,
        title: options.title || '确认',
        variant: options.variant || 'warning',
        confirmText: options.confirmText || '确定',
        onConfirm: () => resolve(true),
        onCancel: () => resolve(false)
      })
    })
  }

  // 纯Toast提示（不显示模态框）
  toast(message, options = {}) {
    return toastService.show(message, {
      title: options.title || '',
      variant: options.variant || 'info',
      duration: options.duration || 4000
    })
  }

  // 创建弹窗实例
  createModal(config) {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const app = createApp(CustomModal, {
      visible: true,
      type: config.type,
      title: config.title,
      message: config.message,
      variant: config.variant,
      confirmText: config.confirmText,
      onConfirm: () => {
        config.onConfirm && config.onConfirm()
        this.destroyModal(app, container)
      },
      onCancel: () => {
        config.onCancel && config.onCancel()
        this.destroyModal(app, container)
      },
      onClose: () => {
        this.destroyModal(app, container)
      }
    })

    app.mount(container)
    this.modals.push({ app, container })
  }

  // 销毁弹窗实例
  destroyModal(app, container) {
    app.unmount()
    if (container.parentNode) {
      container.parentNode.removeChild(container)
    }
    
    this.modals = this.modals.filter(modal => 
      modal.app !== app && modal.container !== container
    )
  }

  // 关闭所有弹窗
  closeAll() {
    this.modals.forEach(({ app, container }) => {
      this.destroyModal(app, container)
    })
  }
}

// 创建全局实例
const modalService = new ModalService()

// 添加到 Vue 原型，方便在组件中使用
export default {
  install(app) {
    app.config.globalProperties.$alert = modalService.alert.bind(modalService)
    app.config.globalProperties.$confirm = modalService.confirm.bind(modalService)
    app.config.globalProperties.$toast = modalService.toast.bind(modalService)
    app.config.globalProperties.$modal = modalService
  }
}

// 导出服务实例，方便在非组件中使用
export { modalService }